<?php

namespace App\Repositories\Criteria;

use App\Models\PlatUser;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

/**
 * Class MchInfoFilterCriteria
 * @package namespace App\Repositories\Criteria;
 */
class MchInfoFilterCriteria implements CriteriaInterface
{
    protected $mchInfo;
    protected $fields;
    protected $isLike;
    protected $relation;

    public function __construct($mchInfo, array $likeFields = [], $isLike = true, $relation = 'platuser' )
    {
        $this->mchInfo = $mchInfo;
        $this->fields = $likeFields;
        $this->isLike = $isLike;
        $this->relation = $relation;
    }


    /**
     * Apply criteria in query repository
     *
     * @param                     $model
     * @param RepositoryInterface $repository
     *
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        if (strlen($this->mchInfo) != 0) {

            if ( ! $model instanceof PlatUser) {
                $model = $model->whereHas($this->relation, function ($query) {
                    return $query->where(function ($q) {
                        foreach ($this->fields as $field) {
                            $q = $this->isLike
                                ? $q->orWhere($field, 'like', "%{$this->mchInfo}%")
                                : $q->orWhere($field, $this->mchInfo);
                        }
                        return $q;
                    });
                });
            } else {
                $model =  $model->where(function ($q) {
                    foreach ($this->fields as $field) {
                        $q = $this->isLike
                            ? $q->orWhere($field, 'like', "%{$this->mchInfo}%")
                            : $q->orWhere($field, $this->mchInfo);
                    }
                    return $q;
                });
//
//                foreach ($this->fields as $field) {
//                    $model = $this->isLike
//                        ? $model->orWhere($field, 'like', "%{$this->mchInfo}%")
//                        : $model->orWhere($field, $this->mchInfo);
//                }
            }
        }

        return $model;
    }
}
